package com.fausto.learnimprint.core.controller.impl

import com.fausto.learnimprint.core.model.dto.CommonResult
import com.fausto.learnimprint.core.service.ICodeService
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.*

/**
 *
 *
 * 前端控制器
 *
 *
 * @author fausto
 * @since 2022-03-28
 */
@Api(tags = ["邀请码API"], basePath = "/bases")
@PreAuthorize("hasAuthority('ADMIN')")
@RestController
@RequestMapping("/codes")
class CodeController {

    @Autowired
    lateinit var codeService: ICodeService

    /**
     *      生成新邀请码并返回
     */
    @ApiOperation(value = "生成邀请码")
    @PostMapping
    fun generateCode(): CommonResult<Any> {
        return try {
            CommonResult.ok("生成新邀请码成功", codeService.newCode())
        } catch (e: Exception) {
            CommonResult.fail("操作失败", data = e.message)
        }
    }

    /**
     *      分页查询邀请码
     */
    @ApiOperation("分页查询激活码")
    @GetMapping("/{page}/{showCount}")
    fun getCode(
        @ApiParam(value = "页面序号数", example = "1")
        @PathVariable page: Int,
        @ApiParam(value = "展示记录数", example = "5")
        @PathVariable showCount: Int
    ): CommonResult<Any> {
        return if (page < 1 || showCount < 1) {
            CommonResult.fail("参数错误")
        } else try {
            CommonResult.ok("查询成功", codeService.getCacheCode(page, showCount))
        } catch (e: Exception) {
            CommonResult.fail("操作失败", data = e.message)
        }
    }
}